<?php
/**
 * Created by PhpStorm.
 * User: wgx
 * Date: 16/7/19
 * Time: 下午3:48
 * 购物车
 */

namespace frontend\controllers;
use common\components\Myhelpers;
use common\models\Product;
use common\models\ShoppingCart;
use yii;

class ShoppingCartController extends FController
{
    public function init()
    {
        parent::init();
        if(Yii::$app->user->isGuest){
            $this->redirect('/site/login');
            Yii::$app->end();
        }
    }

    /**
     * @desc 单件商品加入购物车
     */
    public function actionAdd(){
        $product_id = (int)Yii::$app->request->post('product_id');
        $product_num = (int)Yii::$app->request->post('product_num');
        $user_id = Yii::$app->user->id;


        do{
            $rs = array('errNo' => 0, 'msg' => '添加成功');

            //获取当前商品信息
            $product = Product::findOne($product_id);
            if( $product && $product_num ){
                //查看购物车是否已有该商品，有则修改，没有增加
                $has_cart = ShoppingCart::find()->where('user_id=:user_id AND product_id=:product_id', [
                    ':user_id'=>$user_id,
                    ':product_id'=>$product_id,
                ])->one();
                if( $has_cart ){
                    $has_cart->product_num = $has_cart->product_num + $product_num;
                    $has_cart->product_price = $product->product_price;
                    $has_cart->update_time = date('Y-m-d H:i:s');
                    if( !$has_cart->save(false) ){
                        $rs = array('errNo' => 2, 'msg' => '加入失败');
                    }
                }else{
                    $new_cart = new ShoppingCart();
                    $new_cart->user_id = $user_id;
                    $new_cart->product_id = $product_id;
                    $new_cart->title = $product->title;
                    $new_cart->img_url = $product->img_url;
                    $new_cart->product_price = $product->product_price;
                    $new_cart->product_num = $product_num;
                    $new_cart->create_time = date('Y-m-d H:i:s');
                    if( !$new_cart->save(false) ){
                        $rs = array('errNo' => 3, 'msg' => '添加失败');
                    }
                }
            }else{
                $rs = array('errNo' => 1, 'msg' => '参数有误');
            }
            if( !$rs['errNo'] ){
                //计算当前购物车的货品
                $sql = "SELECT COUNT(*) FROM `shopping_cart` WHERE `user_id`={$user_id}";
                $nowProduct = Yii::$app->db->createCommand($sql)->queryScalar();
                $rs = array('errNo' => 0, 'msg' => '添加成功', 'nowProduct'=>$nowProduct);
            }
        }while(false);

        exit(json_encode($rs));

    }

    /**
     * @desc 批量加入购物车
     */
    public function actionAddAll(){
        $product_ids = Myhelpers::RemoveXSS(Yii::$app->request->post('product_id'));//可能是多个id，用“-”拼接
        $product_ids = trim($product_ids,'-');
        $product_num = (int)Yii::$app->request->post('product_num');
        $user_id = Yii::$app->user->id;


        do{
            $rs = array('errNo' => 0, 'msg' => '添加成功');

            $arr_ids = explode('-', $product_ids);
            foreach( $arr_ids as $product_id ){
                //获取当前商品信息
                $product = Product::findOne($product_id);
                if( $product && $product_num ){
                    //查看购物车是否已有该商品，有则修改，没有增加
                    $has_cart = ShoppingCart::find()->where('user_id=:user_id AND product_id=:product_id', [
                        ':user_id'=>$user_id,
                        ':product_id'=>$product_id,
                    ])->one();
                    if( $has_cart ){
                        $has_cart->product_num = $has_cart->product_num + $product_num;
                        $has_cart->product_price = $product->product_price;
                        $has_cart->update_time = date('Y-m-d H:i:s');
                        if( !$has_cart->save(false) ){
                            $rs = array('errNo' => 2, 'msg' => '加入失败');
                            exit(json_encode($rs));
                        }
                    }else{
                        $new_cart = new ShoppingCart();
                        $new_cart->user_id = $user_id;
                        $new_cart->product_id = $product_id;
                        $new_cart->title = $product->title;
                        $new_cart->img_url = $product->img_url;
                        $new_cart->product_price = $product->product_price;
                        $new_cart->product_num = $product_num;
                        $new_cart->create_time = date('Y-m-d H:i:s');
                        if( !$new_cart->save(false) ){
                            $rs = array('errNo' => 3, 'msg' => '添加失败');
                            exit(json_encode($rs));
                        }
                    }
                }else{
                    $rs = array('errNo' => 1, 'msg' => '参数有误');
                    exit(json_encode($rs));
                }
                if( !$rs['errNo'] ){
                    //计算当前购物车的货品
                    $sql = "SELECT COUNT(*) FROM `shopping_cart` WHERE `user_id`={$user_id}";
                    $nowProduct = Yii::$app->db->createCommand($sql)->queryScalar();
                    $rs = array('errNo' => 0, 'msg' => '添加成功', 'nowProduct'=>$nowProduct);
                }
            }
        }while(false);

        exit(json_encode($rs));
    }

    //ajax从购物车删除
    public function actionDelete(){
        $user_id = Yii::$app->user->id;
        $db = Yii::$app->db;
        do{
            $id = Myhelpers::RemoveXSS(Yii::$app->request->post('id'));
            $id = trim($id, '-');
            $id = str_replace('-', ',', $id);

            if( !$id ) {
                $rs = array('errNo' => 1, 'msg' => '参数有误');
            }else {
                $sql = "DELETE FROM `shopping_cart` WHERE `user_id`={$user_id} AND `id` IN($id)";
                $result = $db->createCommand($sql)->execute();
                if( !$result ) {
                    $rs = array('errNo' => 2, 'msg' => '删除失败');
                }else{
                    //返回购物车还剩几件商品
                    $sql = "SELECT SUM(`product_price`*`product_num`) `total_price`, SUM(`product_num`) `total_num`, COUNT(*) `count_carts`  FROM `shopping_cart` WHERE `user_id`={$user_id}";
                    $total = $db->createCommand($sql)->queryOne();
                    $rs = array('errNo' => 0, 'msg' => '删除成功', 'total_price'=>$total['total_price'], 'total_num'=>$total['total_num'], 'count_carts'=>$total['count_carts']);
                }
            }
        }while(false);

        exit(json_encode($rs));
    }

}